# coding: utf-8
from datetime import datetime
from django.db import models
from lib.common import BasicManager
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


class ModelManagerRole(BasicManager):
    # 获取vip列表
    def get_role_list(self, page, is_show=None, rtype=None):
        result = self.values().order_by("-created_at")
        if is_show:
            result = result.filter(is_show=is_show)
        if rtype:
            result = result.filter(types=rtype)
        if not page:
            return {'retcode': 0, 'retlist': list(result)}
        paginator = Paginator(result, 15)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_role(self, role_id, is_show):
        return self.get(is_show=is_show, id=role_id)

    def get_name_list(self):
        res = self.filter(is_show=1).values()
        return list(res)

    def get_course_dict(self):
        res = self.filter(types__in=[2, 3], is_show=1).values('id', 'card_name')
        res_dict = {k['id']:k['card_name'] for k in res}
        return res_dict

    def get_role_for_id(self, role_id):
        return self.filter(id=role_id).values(
            'id', 'name', 'charge', 'desc', 'thumb', 'detail',
            'poster', 'original_charge','card_name', 'is_show',
        ).first()

    def get_course_list(self, types_list, page=0):
        """获取优势课程（学籍卡+课程卡）"""
        res = self.filter(types__in=types_list, is_show=1).values(
            'id', 'name', 'sort', 'charge',
            'original_charge', 'desc', 'thumb', 'card_name'
        ).order_by('-sort')
        paginator = Paginator(res, 10)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_after_live_goods(self, page, ids):
        res = self.filter(is_show=1, types__in=[1, 2, 3]).values(
            'id', 'name', 'sort', 'charge',
            'original_charge', 'desc', 'thumb', 'card_name'
        ).order_by('-sort')
        if ids:
            res = res.exclude(id__in=ids)
        paginator = Paginator(res, 10)
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}

    def get_live_goods_list(self, page):
        """
        直播添加商品列表
        :param page:
        :return:
        """
        import json
        res = self.filter(types__in=[1, 2, 3], is_show=1).values(
            'id', 'name', 'sort', 'charge',
            'original_charge', 'desc', 'thumb', 'card_name', 'sku'
        ).order_by('-sort')
        paginator = Paginator(res, 10)
        # [{"name": "思维营A", "charge": 2, "original_charge" :100},{"name": "思维营B", "charge": 4, "original_charge" :200}]
        # [{"name": "思维营A", "charge": 90, "original_charge" :100},{"name": "思维营B", "charge": 90, "original_charge" :100}]
        try:
            result_page = paginator.page(page)
        except PageNotAnInteger:
            result_page = paginator.page(1)
        except EmptyPage as e:
            return {'retlist': [], 'curpageidx': page,
                    'hasnext': False, 'hasprevious': False}
        for v in result_page:
            if v['sku']:
                key_of_min_val = min(json.loads(v['sku']), key=lambda x: x['charge'])
                v['charge'] = key_of_min_val['charge']
                v['stock'] = 500
        return {'retlist': list(result_page), 'curpageidx': page,
                'hasnext': result_page.has_next(), 'hasprevious': result_page.has_previous(),
                'total_page': paginator.num_pages}


class Role(models.Model):
    sort = models.IntegerField("排序", default=0)
    name = models.CharField("名称", max_length=50)    # 课程名称
    is_show = models.PositiveSmallIntegerField("是否显示", default=0)
    charge = models.IntegerField('价格', default=0)  # 单位：分
    expire_days = models.IntegerField("时长", default=0)
    types = models.PositiveSmallIntegerField("类型", default=1)  # 类型  1:课程VIP399  2:优势大学卡1499, 3: 课程列表
    original_charge = models.IntegerField("划线价格", default=0)
    desc = models.CharField("课程简介", max_length=200, blank=True)
    thumb = models.ImageField("封面图", max_length=200, default='', blank=True)
    detail = models.TextField("课程详情", default='', blank=True)
    wechat = models.CharField("老师微信", max_length=200, default='', blank=True)
    poster = models.CharField("分享海报", max_length=200, default='', blank=True)
    created_at = models.DateTimeField("添加时间", auto_now_add=True)
    updated_at = models.DateTimeField("修改时间", auto_now=True)
    card_name = models.CharField('卡名称', max_length=50, default='')
    commission = models.IntegerField("佣金比例(%)", default=0, blank=True)
    sku = models.TextField("商品sku", default='', blank=True)  # [{"name": "思维营", "charge": 90, "original_charge" :100}]

    objects = ModelManagerRole()

    class Meta:
        verbose_name = ''
        verbose_name_plural = verbose_name
        db_table = "momself_role"

    def __str__(self):
        return self.name


mm_Role = Role.objects
